import React, { Ref, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { Button, Form, Row, Col, Input, TreeSelect, Select, InputNumber, message, Spin } from 'antd';

import { OneModal } from '@/components/one-ui';
import { departmentAPI, IDeptModalRef } from '../../type';

// import ScrollBarLayout from '@/components/ScrollBarLayout';
import pageStyles from '@/common/pageLayout.less';
import AdminAriea from '@/components/AdminAriea/index';

import formStyles from '../addEditInfoSty.less';
import MyIcon from '@/components/MyIcon';
import { useRequest } from 'umi';
import { getDeptDetailInfo, useDeptAddEdit } from '../../hooks';
import { arieaEchoRender, treeSelectIconTransform } from '@/utils/myutil';
import { getCompanyID, getPosIDs, getTenantID, getUserDepID, getUserID } from '@/utils';
import { RegularExpression } from '@/common/constVariable';
import { DeptContext } from '../../hooks';
import { addDepartment, editDepartment } from '../../service';

const AddEditDeptModal = React.forwardRef(
  (
    {
      onClose,
      visible,
      recordEdit, //有数据是编辑,没有是新增
      selectColumnRow, //表格选中状态的数据
      selectColumnKey, //表格选中状态的key
      superiorDept, //组织机构树,
      onReload, //刷新管理页面
    }: departmentAPI.IAddEditModal,
    ref,
  ) => {
    const deptModalRef: Ref<IDeptModalRef> = useRef(null); //弹框的ref
    const { viewId, curRes } = useContext(DeptContext);

    const { deptDetailInfo, deptLoading } = getDeptDetailInfo(recordEdit);

    // 获取数据字典和省市县数据
    const { MapList, areadList, mapLoading } = useDeptAddEdit({}, curRes);

    // 保存搜索框输入的值
    const [treeSearch, setTreeSearch] = useState<string>('');

    // 机构类型 是否可编辑
    const [cateChanage, setCateChanage] = useState<boolean>(false);
    const onTrueCate = useCallback(() => {
      setCateChanage(true);
    }, [cateChanage]);
    const onFalseCate = useCallback(() => {
      setCateChanage(false);
    }, [cateChanage]);

    // 初始化
    useEffect(() => {
      if (deptDetailInfo && deptDetailInfo?.id) {
        onTrueCate();
        deptForm.setFieldsValue({
          ...deptDetailInfo,
          contaNode: arieaEchoRender(deptDetailInfo),
        });
      } else if (selectColumnRow?.id && selectColumnRow?.category == '1') {
        onTrueCate();
      } else {
        onFalseCate();
      }
    }, [selectColumnRow?.category, deptDetailInfo?.category]);

    // 保存选中隶属节点的 companyID
    const [saveCompany, setSaveCompany] = useState<string>('');
    const setCompanyID = useCallback(
      (comID: string) => {
        setSaveCompany(comID);
      },
      [saveCompany],
    );

    // form表单的ref
    const deptFormRef: any = React.useRef();

    // 声明表单form
    const [deptForm] = Form.useForm();
    // useImperativeHandle(ref, () => ({
    //   // validateFields: deptForm.validateFields,
    //   // setFieldsValue: deptForm.setFieldsValue,
    //   form: deptForm
    // }));

    // 获取省市县数据
    const getAreadList = () => {
      if (areadList && areadList?.data && areadList?.data?.msgFlag) {
        return areadList?.data?.obj;
      } else {
        return [];
      }
    };

    // 保存选中的省市县数据
    const [selectArea, setSelectArea] = useState<any>([]);
    const saveSelectArea = useCallback(
      (areaList) => {
        setSelectArea(areaList);
      },
      [selectArea],
    );

    // 处理树数据
    const handleSelectTree = (list: any) => {
      return list?.map((item: any) => {
        const index = item?.name ? item?.name.indexOf(treeSearch) : -1;
        const beforeStr = item?.name ? item?.name.substr(0, index) : '';
        const afterStr = item?.name ? item?.name.substr(index + treeSearch.length) : '';
        const title =
          index > -1 && treeSearch != '' ? (
            <span>
              {beforeStr}
              <span style={{ color: '#f50' }}>{treeSearch}</span>
              {afterStr}
            </span>
          ) : (
            <span>{item?.name}</span>
          );

        if (item?.children && item?.children?.length > 0) {
          return (
            <TreeSelect.TreeNode
              title={
                <span>
                  {item?.category == 0 ? <MyIcon type={'icon-bank'} /> : <MyIcon type={'icon-cluster'} />}
                  &nbsp;
                  {title}
                </span>
              }
              key={item?.id}
              value={item?.id}
              searchTitle={item?.name}
              companyID={item?.companyID}
              itemRef={{ ...item }}
            >
              {handleSelectTree(item.children)}
            </TreeSelect.TreeNode>
          );
        } else {
          return (
            <TreeSelect.TreeNode
              title={
                <span>
                  {item?.category == 0 ? <MyIcon type={'icon-bank'} /> : <MyIcon type={'icon-cluster'} />}
                  &nbsp;
                  {title}
                </span>
              }
              key={item?.id}
              value={item?.id}
              searchTitle={item?.name}
              companyID={item?.companyID}
              itemRef={{ ...item }}
            />
          );
        }
      });
    };

    // 获取搜索框输入的值
    const treeSearchValue = (valText: string) => {
      setTreeSearch(valText);
    };

    //选则区域后回调
    const selectAreaCallback = (selectArea: any) => {
      saveSelectArea(selectArea);
    };

    /* 关闭弹窗 */
    // const onCloseModal = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    const onCloseModal = () => {
      if (deptModalRef) {
        if (deptModalRef.current) {
          if (deptModalRef.current.onModalCancel) {
            deptModalRef.current.onModalCancel();
          }
        }
      }
    };

    // 保存
    const saveDeptAddData = () => {
      deptForm?.validateFields()?.then((values: any) => {
        let provinceCode = values?.contaNode && values?.contaNode[0] ? values?.contaNode[0] : null;
        let cityCode = values?.contaNode && values?.contaNode[1] ? values?.contaNode[1] : null;
        let countyCode = values?.contaNode && values?.contaNode[2] ? values?.contaNode[2] : null;
        if (deptDetailInfo && deptDetailInfo?.id) {
          let editPayload = {
            ...values,
            id: deptDetailInfo?.id,
            versionNum: deptDetailInfo?.versionNum,
            isOpen: deptDetailInfo?.isOpen,
            provinceCode: provinceCode,
            cityCode: cityCode,
            countyCode: countyCode,
            pID: deptDetailInfo?.pID ? values?.pID : 'null',
            modifyerID: getUserID(),
            modifyPositionID: getPosIDs(),
            modifyDepartmentID: getUserDepID(),
            modifyCompanyID: getCompanyID(),
          };
          delete editPayload['contaNode'];
          addDeptData?.run(editPayload);
        } else {
          let addPayload = {
            ...values,
            provinceCode: provinceCode,
            cityCode: cityCode,
            countyCode: countyCode,
            isOpen: 1,
            companyID: saveCompany ? saveCompany : values?.companyID,
          };
          delete addPayload['contaNode'];
          addDeptData?.run(addPayload);
        }
      });
    };

    // 新增 或者编辑 方法
    const addDeptData = useRequest(
      (payload: any) => {
        if (deptDetailInfo && deptDetailInfo?.id) {
          return editDepartment(payload);
        } else {
          return addDepartment(payload);
        }
      },
      {
        manual: true,
        onSuccess: (res: any) => {
          if (res && res?.msgFlag) {
            message?.success(res?.msg);
            onReload();
            onCloseModal();
          } else {
            message?.error(res?.msg);
          }
        },
      },
    );

    // 保存选择隶属机构后 的 companyID
    const getCompanIDOfpid = (value: any, nodeData: any) => {
      if (nodeData?.itemRef) {
        setCompanyID(nodeData?.itemRef?.companyID);

        if (nodeData?.itemRef?.category == '1') {
          onTrueCate();
          deptForm?.setFieldsValue({ category: 1 });
        } else {
          onFalseCate();
        }
      } else {
        setCompanyID('');
      }
    };

    return (
      <OneModal
        ref={deptModalRef}
        open={true}
        getContainer={false}
        title={recordEdit && recordEdit?.id ? '编辑组织机构' : '添加组织机构'}
        width={'40%'}
        onCancel={onClose}
        footer={
          <>
            <div className={formStyles['dept-edit-btn']}>
              <Button onClick={onCloseModal}>取消</Button>
              <Button
                type={'primary'}
                onClick={saveDeptAddData}
                loading={addDeptData?.loading}
                disabled={!mapLoading && getAreadList()?.length > 0 ? false : true}
              >
                保存
              </Button>
            </div>
          </>
        }
        bodyStyle={{
          padding: '5px 0px',
          // height: window.screen.height * 0.45,
        }}
      >
        <Spin spinning={deptLoading}>
          {/* <ScrollBarLayout> */}
          <div className={pageStyles['fromView-styles']} id={viewId}>
            <Form ref={deptFormRef} layout="inline" form={deptForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name={'name'}
                    label="机构名称"
                    rules={[
                      {
                        required: true,
                        message: '请输入机构名称',
                      },
                    ]}
                    initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo.name : undefined}
                  >
                    <Input placeholder={'请输入机构名称'} allowClear />
                  </Form.Item>
                </Col>

                <AdminAriea
                  cascaderData={getAreadList()}
                  colSpan={24}
                  isRequired={true}
                  labelName="行政区域"
                  formName="contaNode"
                  // allDataID={
                  //   deptDetailInfo &&
                  //   deptDetailInfo?.id &&
                  //   (deptDetailInfo.provinceCode ||
                  //     deptDetailInfo.cityCode ||
                  //     deptDetailInfo.countyCode)
                  //     ? [
                  //         deptDetailInfo.provinceCode,
                  //         deptDetailInfo.cityCode,
                  //         deptDetailInfo.countyCode,
                  //       ]
                  //     : []
                  // }
                  areaAll={selectAreaCallback} // 这个是用户选择数据后，会返回的数据 function
                  showSearch={true}
                  fieldNames={{ label: 'text', value: 'id' }}
                  allowClear={true}
                  viewId={viewId}
                />

                <Col span={24}>
                  <Form.Item
                    name={'pID'}
                    label={'隶属机构'}
                    initialValue={
                      deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.pID : selectColumnRow && selectColumnRow?.id ? selectColumnRow?.id : undefined
                    }
                    rules={[
                      {
                        required: deptDetailInfo && deptDetailInfo?.id ? false : true,
                      },
                    ]}
                  >
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchTitle'}
                      placeholder="请选择隶属机构"
                      // allowClear
                      onSearch={treeSearchValue}
                      getPopupContainer={() => document.getElementById(viewId) as any}
                      disabled={deptDetailInfo && deptDetailInfo?.id ? true : false}
                      onSelect={getCompanIDOfpid}
                    >
                      {handleSelectTree(superiorDept)}
                    </TreeSelect>
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="机构类型"
                    name="category"
                    rules={[{ required: true, message: '请选择机构类型别' }]}
                    initialValue={
                      deptDetailInfo && deptDetailInfo?.id
                        ? deptDetailInfo?.category
                        : selectColumnRow?.id && selectColumnRow?.category == '1'
                        ? selectColumnRow?.category
                        : undefined
                    }
                  >
                    <Select
                      placeholder="请选择机构类型"
                      allowClear
                      getPopupContainer={() => document.getElementById(viewId) as any}
                      // disabled={deptDetailInfo && deptDetailInfo?.id && deptDetailInfo?.category == '1' ? true : selectColumnRow?.id && selectColumnRow?.category == '1' ? true : false}
                      disabled={cateChanage}
                    >
                      <Select.Option value={0} key={0}>
                        单位
                      </Select.Option>
                      <Select.Option value={1} key={1}>
                        部门
                      </Select.Option>
                    </Select>
                  </Form.Item>
                </Col>

                <Col md={24} sm={24}>
                  <Form.Item
                    name={'deptType'}
                    label={'机构类别'}
                    // initialValue={
                    //   deptDetailInfo && deptDetailInfo?.id && deptDetailInfo.deptType
                    //     ? deptDetailInfo.deptType
                    //     : undefined
                    // }
                  >
                    {/* <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchTitle'}
                      placeholder="请选择机构类别"
                      allowClear
                      // onSearch={treeSearchValue}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={treeSelectIconTransform(
                        MapList?.data?.obj?.[`${getTenantID()}1002`],
                        <MyIcon type="ic-normal-zidianguanli" />,
                      )}
                      loading={MapList?.data?.msgFlag ? false : true}
                    /> */}
                    <Select placeholder="请选择机构类别" loading={mapLoading}>
                      {MapList?.[`${getTenantID()}1003`]?.map((item: any) => {
                        return (
                          <Select.Option key={item?.id} value={item?.id}>
                            {item?.name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label="简码" name="shortCode" initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.shortCode : undefined}>
                    <Input placeholder="请填写简码" allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label="联系人" name="contactName" initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.contactName : undefined}>
                    <Input placeholder="请输入联系人" allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="联系电话"
                    name="contactPhone"
                    rules={[
                      {
                        pattern: RegularExpression?.phone,
                        message: '请输入联系电话',
                      },
                    ]}
                    initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.contactPhone : undefined}
                  >
                    <Input placeholder="请填写联系电话" allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="企业邮箱"
                    name="emailNum"
                    rules={[
                      {
                        pattern: RegularExpression.email,
                        message: '请输入联系电话',
                      },
                    ]}
                    initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.emailNum : undefined}
                  >
                    <Input placeholder="请填写企业邮箱" />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="邮政编码"
                    name="zipNum"
                    rules={[
                      {
                        pattern: RegularExpression.zipCode,
                        message: '请输入邮政编码',
                      },
                    ]}
                    initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.zipNum : undefined}
                  >
                    <Input placeholder="请输入邮政编码" allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label="地址" name="address" initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.address : undefined}>
                    <Input placeholder="请输入地址" allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label="排序" name="seq" initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.seq : 0}>
                    <InputNumber placeholder="请输入排序" min={0} />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label="备注" name="remark" initialValue={deptDetailInfo && deptDetailInfo?.id ? deptDetailInfo?.remark : undefined}>
                    <Input placeholder="请输入备注" allowClear />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item
                style={{ display: 'none' }}
                name="companyID"
                initialValue={
                  deptDetailInfo?.id && deptDetailInfo?.companyID
                    ? deptDetailInfo?.companyID
                    : selectColumnRow?.id && selectColumnRow?.companyID
                    ? selectColumnRow?.companyID
                    : null
                }
              >
                <Input hidden />
              </Form.Item>
            </Form>
          </div>
        </Spin>
        {/* </ScrollBarLayout> */}
      </OneModal>
    );
  },
);

export default AddEditDeptModal;
// export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
//   permissions: baseLogin?.permissions,
//   navTab,
// }))(AddEditDeptModal);
